#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <opencv2/opencv.hpp>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //deviceList = new QBluetoothDeviceInfo;
    setWindowIcon(QIcon(":/1.png"));
    setWindowTitle("智能协作臂");

    // 创建一个定时器，用于定时捕获图像
     QTimer *timer = new QTimer(this);
     connect(timer, &QTimer::timeout, this, &MainWindow::updateFrame);
     timer->start(30); // 每30毫秒更新一次

     // 初始化视频捕捉
     cap.open(1);


    socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol);
    connect(socket, &QBluetoothSocket::connected, this, [this]() {
            qDebug() << "已连接到设备";
            // 可以在这里进行连接成功后的其他操作，比如更新 UI 状态
            ui->statusbar->showMessage("蓝牙连接成功");
        });
        connect(socket, &QBluetoothSocket::disconnected, this, [this]() {
            qDebug() << "已从设备断开连接";
            // 更新 UI 状态
            ui->statusbar->showMessage("蓝牙已断开连接");
        });
    discoveryAgent = new QBluetoothDeviceDiscoveryAgent(this);
       //搜索蓝牙设备时，将发现的蓝牙设备添加进列表中显示
    connect(discoveryAgent, &QBluetoothDeviceDiscoveryAgent::deviceDiscovered, this, &MainWindow::addDeviceToList);
       //提示搜索完成
   connect(discoveryAgent, &QBluetoothDeviceDiscoveryAgent::finished, this, &MainWindow::TS);
       //点击搜索按钮时，调用startSearch函数来启动蓝牙搜索
    connect(ui->pushButton_3, &QPushButton::clicked, this, &MainWindow::startSearch);
    //双击listwidget连接蓝牙
    connect(ui->listWidget,&QListWidget::itemDoubleClicked,this,&MainWindow::connectToSelectedDevice);

}

MainWindow::~MainWindow()
{
    delete ui;
}


//void MainWindow::on_pushButton_3_clicked()//蓝牙搜索
//{
//    startSearch();
//    addDeviceToList();
//}

void MainWindow::updateFrame()
{
    Mat frame;
    if (cap.isOpened())
    {
        cap >> frame; // 捕获图像
        if (!frame.empty())
        {
            // 将OpenCV的Mat转换为QImage
            cv::cvtColor(frame, frame, COLOR_BGR2RGB); // 转换颜色格式
            QImage img((const unsigned char*)frame.data, frame.cols, frame.rows, QImage::Format_RGB888);
            ui->label->setPixmap(QPixmap::fromImage(img)); // 显示在QLabel上
        }
    }
}


void MainWindow::startSearch()//启动蓝牙搜索
{
    //deviceList->clear();//清空设备列表
    ui->listWidget->clear();//清空列表视图
    discoveryAgent->start();//启动搜索蓝牙设备

}

void MainWindow::TS()
{
    QMessageBox::information(nullptr, "提示", "搜索完成！");
}

void MainWindow::connectToSelectedDevice(QListWidgetItem *item)
{
          qDebug() << "开始连接设备...";
          QBluetoothDeviceInfo device = item->data(Qt::UserRole).value<QBluetoothDeviceInfo>();

          QBluetoothUuid serviceUuid(QBluetoothUuid::SerialPort);

          qDebug() << "尝试连接到设备:" << device.name() << "地址:" << device.address() << "服务 UUID:" << serviceUuid.toString();

          socket->connectToService(device.address(), serviceUuid);

          connect(socket, &QBluetoothSocket::connected, this, [this, device]() {
              qDebug() << "已连接到设备" << device.name();
              QMessageBox::information(nullptr, "提示", "蓝牙已连接！");
              // 更新 UI 状态
              ui->statusbar->showMessage("蓝牙连接成功");
          });

          connect(socket, &QBluetoothSocket::disconnected, this, [this, device]() {
              qDebug() << "已从设备" << device.name() << "断开连接";
              // 更新 UI 状态
              ui->statusbar->showMessage("蓝牙已断开连接");
          });
}


void MainWindow::addDeviceToList(const QBluetoothDeviceInfo &device)//将发现的设备添加进列表当中
{
        QString deviceName = device.name().isEmpty()? device.address().toString() : device.name();
        QListWidgetItem *item = new QListWidgetItem(deviceName);
        item->setData(Qt::UserRole, QVariant::fromValue(device));
        ui->listWidget->addItem(item);
}


void MainWindow::on_pushButton_6_pressed()
{
    QBluetoothAddress address("00:22:04:01:03:1D");
    socket->connectToService(address, QBluetoothUuid::SerialPort);
    QByteArray dataToSend = "0";
    qint64 bytesWritten = socket->write(dataToSend);
    if (bytesWritten < 0) {
        qDebug() << "Failed to write data to bluetooth device.";
    } else {
        qDebug() << "Data sent successfully. Bytes written: " << bytesWritten;
    }
}

void MainWindow::on_pushButton_8_pressed()
{
    QBluetoothAddress address("00:22:04:01:03:1D");
    socket->connectToService(address, QBluetoothUuid::SerialPort);
    QByteArray dataToSend = "2";
    qint64 bytesWritten = socket->write(dataToSend);
    if (bytesWritten < 0) {
        qDebug() << "Failed to write data to bluetooth device.";
    } else {
        qDebug() << "Data sent successfully. Bytes written: " << bytesWritten;
    }
}

void MainWindow::on_pushButton_7_pressed()
{
    QBluetoothAddress address("00:22:04:01:03:1D");
    socket->connectToService(address, QBluetoothUuid::SerialPort);
    QByteArray dataToSend = "1";
    qint64 bytesWritten = socket->write(dataToSend);
    if (bytesWritten < 0) {
        qDebug() << "Failed to write data to bluetooth device.";
    } else {
        qDebug() << "Data sent successfully. Bytes written: " << bytesWritten;
    }
}

void MainWindow::on_pushButton_9_pressed()
{
    QBluetoothAddress address("00:22:04:01:03:1D");
    socket->connectToService(address, QBluetoothUuid::SerialPort);
    QByteArray dataToSend = "3";
    qint64 bytesWritten = socket->write(dataToSend);
    if (bytesWritten < 0) {
        qDebug() << "Failed to write data to bluetooth device.";
    } else {
        qDebug() << "Data sent successfully. Bytes written: " << bytesWritten;
    }
}

void MainWindow::on_pushButton_10_pressed()
{
    QBluetoothAddress address("00:22:04:01:03:1D");
    socket->connectToService(address, QBluetoothUuid::SerialPort);
    QByteArray dataToSend = "4";
    qint64 bytesWritten = socket->write(dataToSend);
    if (bytesWritten < 0) {
        qDebug() << "Failed to write data to bluetooth device.";
    } else {
        qDebug() << "Data sent successfully. Bytes written: " << bytesWritten;
    }
}

void MainWindow::on_pushButton_12_pressed()
{
    QBluetoothAddress address("00:22:04:01:03:1D");
    socket->connectToService(address, QBluetoothUuid::SerialPort);
    QByteArray dataToSend = "5";
    qint64 bytesWritten = socket->write(dataToSend);
    if (bytesWritten < 0) {
        qDebug() << "Failed to write data to bluetooth device.";
    } else {
        qDebug() << "Data sent successfully. Bytes written: " << bytesWritten;
    }
}

void MainWindow::on_pushButton_13_pressed()
{
    QBluetoothAddress address("00:22:04:01:03:1D");
    socket->connectToService(address, QBluetoothUuid::SerialPort);
    QByteArray dataToSend = "6";
    qint64 bytesWritten = socket->write(dataToSend);
    if (bytesWritten < 0) {
        qDebug() << "Failed to write data to bluetooth device.";
    } else {
        qDebug() << "Data sent successfully. Bytes written: " << bytesWritten;
    }
}

void MainWindow::on_pushButton_14_pressed()
{
    QBluetoothAddress address("00:22:04:01:03:1D");
    socket->connectToService(address, QBluetoothUuid::SerialPort);
    QByteArray dataToSend = "7";
    qint64 bytesWritten = socket->write(dataToSend);
    if (bytesWritten < 0) {
        qDebug() << "Failed to write data to bluetooth device.";
    } else {
        qDebug() << "Data sent successfully. Bytes written: " << bytesWritten;
    }
}

void MainWindow::on_pushButton_15_pressed()
{
    QBluetoothAddress address("00:22:04:01:03:1D");
    socket->connectToService(address, QBluetoothUuid::SerialPort);
    QByteArray dataToSend = "8";
    qint64 bytesWritten = socket->write(dataToSend);
    if (bytesWritten < 0) {
        qDebug() << "Failed to write data to bluetooth device.";
    } else {
        qDebug() << "Data sent successfully. Bytes written: " << bytesWritten;
    }
}

void MainWindow::on_pushButton_16_pressed()
{
    QBluetoothAddress address("00:22:04:01:03:1D");
    socket->connectToService(address, QBluetoothUuid::SerialPort);
    QByteArray dataToSend = "9";
    qint64 bytesWritten = socket->write(dataToSend);
    if (bytesWritten < 0) {
        qDebug() << "Failed to write data to bluetooth device.";
    } else {
        qDebug() << "Data sent successfully. Bytes written: " << bytesWritten;
    }
}

void MainWindow::on_pushButton_17_pressed()
{
    QBluetoothAddress address("00:22:04:01:03:1D");
    socket->connectToService(address, QBluetoothUuid::SerialPort);
    QByteArray dataToSend = "a";
    qint64 bytesWritten = socket->write(dataToSend);
    if (bytesWritten < 0) {
        qDebug() << "Failed to write data to bluetooth device.";
    } else {
        qDebug() << "Data sent successfully. Bytes written: " << bytesWritten;
    }
}

void MainWindow::on_pushButton_18_pressed()
{
    QBluetoothAddress address("00:22:04:01:03:1D");
    socket->connectToService(address, QBluetoothUuid::SerialPort);
    QByteArray dataToSend = "b";
    qint64 bytesWritten = socket->write(dataToSend);
    if (bytesWritten < 0) {
        qDebug() << "Failed to write data to bluetooth device.";
    } else {
        qDebug() << "Data sent successfully. Bytes written: " << bytesWritten;
    }
}
